package main

import (
	"fmt"
	_ "gitee.com/chunanyong/dm"
	"gitee.com/chunanyong/zorm"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"zorm-learn/app/middleware"
	"zorm-learn/app/router"
	"zorm-learn/app/task"
	"zorm-learn/app/util"
	_ "zorm-learn/docs"
)

var server *util.Server

func init() {
	var db *zorm.DBDao
	var err error
	config0, config1, config2, serverConfig, taskConfig, err := util.ReadConfig()
	if err != nil {
		fmt.Errorf("数据库连接异常 %v", err)
		panic(any(err.Error()))
	}
	db, err = zorm.NewDBDao(config0)
	if err != nil {
		fmt.Errorf("数据库连接异常 %v", err)
		panic(any(err.Error()))
	}
	util.MainCtx.DB = db
	dataSources := make([]*zorm.DBDao, 0)
	dataSources = append(dataSources, db)
	if len(config1.DSN) > 10 {
		db1, err := zorm.NewDBDao(config1)
		if err == nil {
			dataSources = append(dataSources, db1)
		}
	}
	if len(config2.DSN) > 10 {
		db2, err := zorm.NewDBDao(config2)
		if err == nil {
			dataSources = append(dataSources, db2)
		}
	}
	util.MainCtx.DataSources = dataSources
	server = serverConfig
	middleware.InitLogger(server.LogLevel)

	task.RunScheduleTask(taskConfig)
}

func main() {
	// 静态资源http服务
	// StaticHttpServer()

	r := gin.Default()
	r.Use(middleware.GinLogger(util.MainCtx.Logger)) //, middleware.GinRecovery(util2.MainCtx.Logger, true))
	//	r.Use(loginRequired())
	/*f, _ := os.Create("logs/gin.log")
	gin.DefaultWriter = io.MultiWriter(f,os.Stdout)*/
	v := r.Group("/api/v1")
	for _, f := range router.NoCheckRole {
		f(v)
	}
	util.MainCtx.RouterGroup = v

	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	if len(server.Port) != 0 {
		r.Run(":" + server.Port)
	} else {
		r.Run()
	}

}

func StaticHttpServer() {
	engine := gin.Default()
	engine.Static("/", "./dist")
	go engine.Run(":8888")
}
